/*
 * Copyright (c) 2021. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.kason.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @author 卢清波
 * @date 2021/1/27 14:43
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String>
{

    static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception
    {
        String s = ctx.channel().remoteAddress().toString().replaceAll("\\/127\\.0\\.0\\.1\\:", "");
        String s1 = "【客户端】" + s;
        Channel channel = ctx.channel();
        channelGroup.stream().forEach(ch->{
            if(channel!=ch)
            {
                ch.writeAndFlush(s1+"发送消息："+msg+"_");
            }else{
                ch.writeAndFlush("自己发送了消息："+msg+"_");
            }
        });
    }

    // channel 上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        String s = ctx.channel().remoteAddress().toString().replaceAll("\\/127\\.0\\.0\\.1\\:", "");
        String s1 = "【客户端】" + s + "上线了\n";
        System.out.println(s1);
        channelGroup.writeAndFlush(s1);
        if(ctx.channel().isActive())
        {
            channelGroup.add(ctx.channel());
        }
    }

    // channel 下线
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception
    {
        String s = ctx.channel().remoteAddress().toString().replaceAll("\\/127\\.0\\.0\\.1\\:", "");
        String s1 = "【客户端】" + s + "下线了";
        channelGroup.remove(ctx.channel());
        channelGroup.writeAndFlush(s1);
    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ctx.close();
    }




}
